package info.motteke.kurumi.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

import info.motteke.kurumi.Window;
import info.motteke.util.MixiVoiceProperties;

public class SwtWindow implements Window {

    private final Display display;

    private final Shell parent;

    private final Tray tray;

    public SwtWindow() {
        display = new Display();
        parent = createShell();

        tray = display.getSystemTray();
        TrayItem trayItem = new TrayItem(tray, SWT.NONE);
        trayItem.setImage(new Image(display, getClass().getClassLoader().getResourceAsStream("tray.png")));
        trayItem.addSelectionListener(new TraySelectionListener(parent));
        trayItem.addListener(SWT.MenuDetect, new TrayMenuListener(parent));
    }

    public Display getDisplay() {
        return display;
    }

    public Shell getShell() {
        return parent;
    }

    private Shell createShell() {
        MixiVoiceProperties prop = MixiVoiceProperties.getInstance();

        final Shell shell = new Shell(display);
        shell.setText("くるみ");
        shell.setLayout(new FillLayout());
        shell.setSize(prop.getWindowWidth(), prop.getWindowHeight());
        shell.addControlListener(new ShellResizeListener(shell));
        shell.addShellListener(new ShellCloseListener(shell));

        return shell;
    }

    @Override
    public void start() {
        parent.open();

        while (!parent.isDisposed()) {
            if(!display.readAndDispatch()){
                display.sleep();
            }
        }
        tray.dispose();
        display.dispose();
    }

}
